﻿using AdminWeb.Areas.Sys.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using XW.Core;
using XW.Data;
using XW.Utils;
using XW.Web.Framework;

namespace AdminWeb.Areas.Sys.Controllers
{
    [Area("Sys")]
    [Authorize]
    public class OrgController : BaseController
    {
        private readonly SqlSugarRepository<SysOrg> _orgRep;
        private readonly ILogger<OrgController> _logger;
        public OrgController(ILogger<OrgController> logger, SqlSugarRepository<SysOrg> orgRep)
        {
            this._orgRep = orgRep;
            this._logger = logger;
        }
        public IActionResult List()
        {
            return View();
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> AllListAsync()
        {
            var pageModel = CommonHelper.GetPageModel<OrgPageModel>("sort", "asc");
            RefAsync<int> count = 0;
            var query = _orgRep.AsQueryable();
            query.Where(d => d.IsDelete == false);
            // 关键字查询
            query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.Name.Contains(pageModel.Keyword)
                || u.Remark.Contains(pageModel.Keyword)
                || u.Code.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            else
            {
                query.OrderBy(d => d.Sort);
            }

            // 排序
            var list = await query.ToListAsync();

            return GetSuccessResult(list);
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(long id = 0)
        {
            SysOrg org = null;
            if (id > 0)
            {
                org = _orgRep.GetById(id);
                if (org == null)
                {
                    return Content("<h1>数据不存在！</h1>");
                }
            }
            else
            {
                org = new SysOrg();
            }

            //ViewData["CurrentUser"] = user;
            return View(org);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public IActionResult Save()
        {
            long id = CommonHelper.ToInt64(this.Request.Form["id"]);
            string Name = this.Request.Form["Name"]; // 菜单名
            string Code = this.Request.Form["Code"]; 
            string OrgType = this.Request.Form["OrgType"];
            long ParentId = CommonHelper.ToInt64(this.Request.Form["ParentId"]);
 
            string Remark = this.Request.Form["Remark"]; 
            int Status = CommonHelper.ToInt(this.Request.Form["Status"]); 
            int Sort = CommonHelper.ToInt(this.Request.Form["Sort"]);  // 排序



            if (Name.IsNullOrEmpty())
            {
                return GetErrorResult("菜单名不能为空");
            }

            if (id == 0)
            {
                var menu = new SysOrg();
                menu.Name = Name;
                menu.Code = Code;
                menu.OrgType = OrgType;
                menu.Sort = Sort;
                menu.ParentId = ParentId;
                menu.Remark = Remark;
                menu.Status = Status; 
                menu.IsDelete = false;
                _orgRep.Insert(menu);
            }
            else
            {
                //// 检查是否循环
                //if (CheckIsCircularMenu(id, ParentId))
                //{
                //    return GetErrorResult("父菜单设置错误，引发循环引用！");
                //}
                _orgRep.AsUpdateable()
                    .SetColumns(u => u.Name == Name)
                    .SetColumns(u => u.Code == Code) 
                    .SetColumns(u => u.ParentId == ParentId)
                    .SetColumns(u => u.Remark == Remark)
                    .SetColumns(u => u.Status == Status)
                    .SetColumns(u => u.OrgType == OrgType)
                    .SetColumns(u => u.Sort == Sort)
                   .setColumnsUpdateUserAndTime()
                   .Where(u => u.Id == id).ExecuteCommand();
            }

            return GetSuccessResult("保存成功！");

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Delete(long id = 0)
        {
            SysOrg menu = _orgRep.GetById(id);
            if (menu == null)
            {
                return GetErrorResult("菜单不存在");
            }
            var result = await _orgRep.DeleteByIdAsync(id);
            return GetSuccessResult("操作成功！");
        }

    }
}
